<template>
  <div class="dashboard-container">
    <!-- 核心指标卡片 -->
    <div class="metrics-grid">
      <div v-for="(metric, index) in metrics" :key="index" class="metric-card">
        <div class="metric-icon">
          <el-icon :size="24" :color="metric.color">
            <component :is="metric.icon" />
          </el-icon>
        </div>
        <div class="metric-content">
          <div class="metric-title">{{ metric.title }}</div>
          <div class="metric-value">{{ metric.value }}</div>
          <div class="metric-trend" :class="metric.trend > 0 ? 'up' : 'down'">
            <span class="trend-prefix">相较于昨日：</span>
            <el-icon>
              <component :is="metric.trend > 0 ? 'ArrowUp' : 'ArrowDown'" />
            </el-icon>
            {{ Math.abs(metric.trend) }}%
            <span class="trend-label">{{ metric.trend > 0 ? '增长' : '下降' }}</span>
          </div>
        </div>
        <div class="metric-chart" ref="miniChartRefs"></div>
      </div>
    </div>

    <!-- 图表网格 -->
    <div class="charts-grid">
      <!-- 借阅趋势迷你图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h4>近期借阅趋势</h4>
          <el-tag size="small">最近7天</el-tag>
        </div>
        <div ref="trendChartRef" class="chart-content"></div>
      </div>

      <!-- 分类占比迷你图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h4>图书分类占比</h4>
          <el-tag size="small">实时数据</el-tag>
        </div>
        <div ref="categoryChartRef" class="chart-content"></div>
      </div>

      <!-- 热门图书TOP5 -->
      <div class="chart-card">
        <div class="chart-header">
          <h4>热门图书TOP5</h4>
          <el-tag size="small">本月</el-tag>
        </div>
        <div ref="popularChartRef" class="chart-content"></div>
      </div>

      <!-- 读者活跃度 -->
      <div class="chart-card">
        <div class="chart-header">
          <h4>读者活跃度</h4>
          <el-tag size="small">本周</el-tag>
        </div>
        <div ref="activityChartRef" class="chart-content"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import {
  Reading,
  Tickets,
  User,
  Warning,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import { getCoreMetrics, getDashboardBorrowingTrend, getCategoryProportion, getPopularBooksTop5, getDashboardReaderBehavior } from '@/api/statistics'

const metrics = ref([
  {
    title: '总借阅量',
    value: '0',
    trend: 0,
    color: '#409EFF',
    icon: Reading
  },
  {
    title: '当前借出数',
    value: '0',
    trend: 0,
    color: '#67C23A',
    icon: Tickets
  },
  {
    title: '逾期数量',
    value: '0',
    trend: 0,
    color: '#F56C6C',
    icon: Warning
  },
  {
    title: '新增用户数',
    value: '0',
    trend: 0,
    color: '#E6A23C',
    icon: User
  }
])

const miniChartRefs = ref([])
const trendChartRef = ref(null)
const categoryChartRef = ref(null)
const popularChartRef = ref(null)
const activityChartRef = ref(null)

let charts = {
  miniCharts: [],
  trendChart: null,
  categoryChart: null,
  popularChart: null,
  activityChart: null
}

const initCharts = () => {
  // 初始化迷你图表
  miniChartRefs.value.forEach((el, index) => {
    const chart = echarts.init(el)
    charts.miniCharts[index] = chart
    
    const option = {
      grid: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
      },
      xAxis: {
        type: 'category',
        show: false,
        boundaryGap: false
      },
      yAxis: {
        type: 'value',
        show: false
      },
      series: [{
        type: 'line',
        data: generateRandomData(7),
        smooth: true,
        symbol: 'none',
        lineStyle: {
          color: metrics.value[index].color
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: metrics.value[index].color + '40' },
            { offset: 1, color: metrics.value[index].color + '00' }
          ])
        }
      }]
    }
    chart.setOption(option)
  })

  // 初始化趋势图
  if (trendChartRef.value) {
    charts.trendChart = echarts.init(trendChartRef.value)
    initTrendChart()
  }

  // 初始化分类图
  if (categoryChartRef.value) {
    charts.categoryChart = echarts.init(categoryChartRef.value)
    initCategoryChart()
  }

  // 初始化热门图书图
  if (popularChartRef.value) {
    charts.popularChart = echarts.init(popularChartRef.value)
    initPopularChart()
  }

  // 初始化活跃度图
  if (activityChartRef.value) {
    charts.activityChart = echarts.init(activityChartRef.value)
    initActivityChart()
  }
}

const generateRandomData = (count) => {
  return Array.from({ length: count }, () => Math.floor(Math.random() * 100))
}

// 获取核心指标数据
const fetchCoreMetrics = async () => {
  try {
    const res = await getCoreMetrics()
    if (res.code === 0 && res.data) {
      metrics.value[0].value = res.data.totalBorrowings.value.toString()
      metrics.value[0].trend = res.data.totalBorrowings.trend
      
      metrics.value[1].value = res.data.currentBorrowings.value.toString()
      metrics.value[1].trend = res.data.currentBorrowings.trend
      
      metrics.value[2].value = res.data.overdueItems.value.toString()
      metrics.value[2].trend = res.data.overdueItems.trend
      
      metrics.value[3].value = res.data.newUsers.value.toString()
      metrics.value[3].trend = res.data.newUsers.trend
    }
  } catch (error) {
    console.error('获取核心指标数据失败:', error)
  }
}

// 获取借阅趋势数据
const initTrendChart = async () => {
  try {
    const res = await getDashboardBorrowingTrend()
    console.log('仪表盘借阅趋势数据:', res)  // 添加日志
    if (res.code === 0 && res.data) {
      const option = {
        grid: {
          top: 30,
          right: 20,
          bottom: 30,
          left: 60
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>借阅量: {c}'
        },
        xAxis: {
          type: 'category',
          data: res.data.dates,
          axisLabel: {
            formatter: (value) => {
              return value.slice(5)  // 只显示 MM-DD
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '借阅量',
          minInterval: 1  // 设置最小间隔为1，确保显示整数
        },
        series: [{
          name: '借阅量',
          data: res.data.values,
          type: 'line',
          smooth: true,
          showSymbol: true,  // 显示数据点
          symbolSize: 6,     // 设置数据点大小
          lineStyle: {
            color: '#409EFF',
            width: 2
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#409EFF40' },
              { offset: 1, color: '#409EFF00' }
            ])
          }
        }]
      }
      charts.trendChart.setOption(option)
    } else {
      console.error('获取仪表盘借阅趋势数据失败:', res)
    }
  } catch (error) {
    console.error('获取仪表盘借阅趋势数据失败:', error)
  }
}

// 获取并初始化分类占比图表
const initCategoryChart = async () => {
  try {
    const res = await getCategoryProportion()
    if (res.code === 0) {
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        series: [{
          type: 'pie',
          radius: '70%',
          data: res.data.map(item => ({
            name: item.categoryName,
            value: item.count,
            percentage: item.percentage
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            formatter: '{b}: {d}%'
          }
        }]
      }
      charts.categoryChart.setOption(option)
    }
  } catch (error) {
    console.error('获取分类占比数据失败:', error)
  }
}

// 获取并初始化热门图书TOP5图表
const initPopularChart = async () => {
  try {
    const res = await getPopularBooksTop5()
    if (res.code === 0) {
      const option = {
        grid: {
          top: 30,
          right: 20,
          bottom: 30,
          left: 120  // 增加左侧间距以显示完整书名
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}: {c} 热度'
        },
        xAxis: {
          type: 'value',
          name: '借阅次数'
        },
        yAxis: {
          type: 'category',
          data: res.data.map(item => item.bookName).reverse(),  // 反转数组使最高的在最上面
          axisLabel: {
            width: 100,        // 设置标签宽度
            overflow: 'break'  // 文字过长时换行
          }
        },
        series: [{
          type: 'bar',
          data: res.data.map(item => item.borrowCount).reverse(),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          }
        }]
      }
      charts.popularChart.setOption(option)
    }
  } catch (error) {
    console.error('获取热门图书TOP5数据失败:', error)
  }
}

// 获取并初始化读者活跃度图表
const initActivityChart = async () => {
  try {
    const res = await getDashboardReaderBehavior()
    console.log('读者活跃度数据:', res)  // 添加日志
    if (res.code === 0 && res.data) {
      const option = {
        grid: {
          top: 30,
          right: 20,
          bottom: 30,
          left: 60
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>活跃度: {c}'
        },
        xAxis: {
          type: 'category',
          data: res.data.days,
          axisLabel: {
            interval: 0  // 强制显示所有标签
          }
        },
        yAxis: {
          type: 'value',
          name: '活跃度',
          minInterval: 1  // 设置最小间隔为1，确保显示整数
        },
        series: [{
          name: '活跃度',
          data: res.data.activities,
          type: 'bar',
          barWidth: '40%',  // 设置柱子宽度
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              { offset: 0, color: '#67C23A' },
              { offset: 1, color: '#95EB7D' }
            ])
          }
        }]
      }
      charts.activityChart.setOption(option)
    } else {
      console.error('获取读者活跃度数据失败:', res)
    }
  } catch (error) {
    console.error('获取读者活跃度数据失败:', error)
  }
}

onMounted(() => {
  fetchCoreMetrics() // 获取核心指标数据
  initCharts()
  window.addEventListener('resize', () => {
    Object.values(charts).flat().forEach(chart => {
      chart?.resize()
    })
  })
})

onUnmounted(() => {
  Object.values(charts).flat().forEach(chart => {
    chart?.dispose()
  })
  window.removeEventListener('resize', () => {
    Object.values(charts).flat().forEach(chart => {
      chart?.resize()
    })
  })
})
</script>

<style scoped>
.dashboard-container {
  padding: 16px;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
  width: 100%;
}

.metric-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  position: relative;
  height: 120px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.metric-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  background: #f0f9ff;
}

.metric-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.metric-title {
  font-size: 14px;
  color: #909399;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 8px 0;
}

.metric-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.trend-prefix {
  color: #909399;
}

.metric-trend.up {
  color: #67c23a;
}

.metric-trend.down {
  color: #f56c6c;
}

.trend-label {
  color: #909399;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  width: 100%;
  flex: 1;
  min-height: 0;
}

.chart-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  min-height: 300px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.chart-content {
  flex: 1;
  min-height: 250px;
}

@media screen and (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
}

@media screen and (max-width: 768px) {
  .metrics-grid {
    grid-template-columns: 1fr;
  }
}
</style> 